package com.fingard.dsp.bank.directbank.jyrb01;

import java.util.Calendar;
import java.util.Date;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.ITransaction;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7515TodayTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7516HisTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.RetAtsTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.detail.RetAtsTransDetail;
import com.fingard.text.StringHelper;
import com.fingard.util.DateHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

/**
 * Created by aaron on 2018/4/24.
 */
public class JYRB01Transaction extends JYRB01Base implements ITransaction {
    @Override
    public RetAtsTrans d_7516_HisTrans(Req7516HisTrans p_req7516) throws Exception {
        RetAtsTrans retAtsTrans = new RetAtsTrans(p_req7516.reqHeader);
        String tmpRespCode = "";
        String tmpRespInfo = "";
        retAtsTrans.writeStart();

        try {
            //tmpClndrStepTo.get(Calendar.MONTH) MONTH是从0开始编的，意味着0是1月，11是12月
            Calendar tmpCalendarFrom = Calendar.getInstance();
            tmpCalendarFrom.setTime(p_req7516.getDateFrom());

            Calendar tmpCalendarTo = Calendar.getInstance();
            tmpCalendarTo.setTime(p_req7516.getDateTo());

            //int qryCount=0;
            int tmpIntDateFrom = 0;
            int tmpIntDateTo = 0;
            //按自然月循环查询
            while (tmpIntDateFrom <= tmpIntDateTo && tmpRespCode.length() == 0) {
                Calendar tmpClndrStepTo = Calendar.getInstance();
                tmpClndrStepTo.setTime(tmpCalendarFrom.getTime());
                //判断是否跨月
                if (DateHelper.compareMonth(tmpCalendarFrom, tmpCalendarTo) == -1) {
                    //跨月则设置为月末
                    tmpClndrStepTo.set(Calendar.DAY_OF_MONTH, tmpClndrStepTo.getActualMaximum(Calendar.DAY_OF_MONTH));
                } else {
                    tmpClndrStepTo.setTime(tmpCalendarTo.getTime());
                }
                JYRB01Header JYRB01Header = new JYRB01Header();
                JYRB01Header.trsCode = "B2EActTrsQryHx";
                JYRB01Header.ERPTrsTimestamp = p_req7516.reqHeader.transTime;
                XmlTextWriter xmlTextWriter = new XmlTextWriter();
                wirteCommenHeader(xmlTextWriter, JYRB01Header);
                xmlTextWriter.writeStartElement("Body");
                xmlTextWriter.writeStartElement("List");
                xmlTextWriter.writeStartElement("Map");
                xmlTextWriter.writeElementString("AcNo", p_req7516.actNum);
                xmlTextWriter.writeElementString("BeginDate", Format.Date8Format.format(tmpCalendarFrom.getTime()));
                xmlTextWriter.writeElementString("EndDate", Format.Date8Format.format(tmpClndrStepTo.getTime()));
                xmlTextWriter.writeEndDocument();
                String[] bankResult = sendToBank(xmlTextWriter.toXmlString(), JYRB01Header.trsCode);
                if (bankResult[0].length() == 0) {
                    StringBuilder tmpSbMsg = new StringBuilder();
                    XmlTextReader tmpBkReader = loadBankRespXmlReader(bankResult[1], tmpSbMsg);
                    if (tmpBkReader != null) {
                        String IBSReturnCode = tmpBkReader.getFirstText("/Message/Head/IBSReturnCode");
                        if ("000000".equals(IBSReturnCode)) {
                            String returnCode = tmpBkReader.getFirstText("/Message/Body/List/Map/ReturnCode");
                            if ("000000".equals(returnCode)) {
                                while (tmpBkReader.read("/Message/Body/List/Map/List/Map")) {
                                    XElement readXElement = tmpBkReader.readedXElement;
                                    RetAtsTransDetail detail = new RetAtsTransDetail();
                                    detail.tranDate = readXElement.getSingleTextNotNull("TransDate").trim();
                                    detail.valueDate = detail.tranDate;
                                    detail.actNum = p_req7516.actNum;
                                    detail.tranTime = detail.tranDate + " " + readXElement.getSingleTextNotNull("TransTime").trim();
                                    detail.comment = readXElement.getSingleTextNotNull("Remark").trim();
                                    String note = readXElement.getSingleTextNotNull("Note").trim();
                                    detail.abstr = pickupAbstr(note);
                                    detail.usage = note;
                                    detail.askNumber = readXElement.getSingleTextNotNull("JnlNo").trim();
                                    detail.recAccNum = readXElement.getSingleTextNotNull("PayeeAcNo").trim();
                                    detail.recAccName = readXElement.getSingleTextNotNull("PayeeAcName").trim();
                                    detail.recAccBank = readXElement.getSingleTextNotNull("UnionDeptId").trim();
                                    detail.cur = convertCurToATS(readXElement.getSingleTextNotNull("Currency").trim());
                                    detail.accBal = readXElement.getSingleTextNotNull("Balance").trim();
                                    detail.tranAmt = readXElement.getSingleTextNotNull("Amount").trim();
                                    String cdFlag = readXElement.getSingleTextNotNull("CRFlag").trim();//c贷d借
                                    if (cdFlag.equals("C")&& detail.tranAmt.startsWith("-")) {
                                        detail.cdFlag = "1";
                                        detail.tranAmt = detail.tranAmt.substring(1);
                                    } else if(cdFlag.equals("D") && detail.tranAmt.startsWith("-")) {
                                        detail.cdFlag = "2";
                                        detail.tranAmt = detail.tranAmt.substring(1);
                                    }else if(cdFlag.equals("D")){
                                        detail.cdFlag = "1";
                                    }else if(cdFlag.equals("C")){
                                        detail.cdFlag = "2";
                                    }else{
                                        tmpRespCode = "-1";
                                        tmpRespInfo = "借贷标志( " + cdFlag + ")无法识别，请与银行核对";
                                        break;
                                    }
                                    retAtsTrans.writeRetDetail(detail);
                                }
                                tmpCalendarFrom = tmpClndrStepTo;
                                tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
                                tmpIntDateFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
                                tmpIntDateTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
                            } else {
                                tmpRespCode = "-1";
                                tmpRespInfo = tmpBkReader.getFirstText("/Message/Body/List/Map/ReturnMsg");
                                break;
                            }
                        } else {
                            tmpRespCode = "-1";
                            tmpRespInfo = tmpBkReader.getFirstText("/Message/Head/IBSReturnMsg");
                            break;
                        }
                    } else {
                        tmpRespCode = "-1";
                        tmpRespInfo = tmpSbMsg.toString();
                        break;
                    }
                } else {
                    tmpRespCode = "-1";
                    tmpRespInfo = bankResult[1];
                    break;
                }
            }
        } catch (Exception ex) {
            tmpRespCode = "-1";
            tmpRespInfo = ex.getMessage();
            ex.printStackTrace();
        }
        if ("-1".equals(tmpRespCode)) {
            retAtsTrans = new RetAtsTrans(p_req7516.reqHeader);
            retAtsTrans.writeStart();//写返回ATS的统一头部信息
            retAtsTrans.writeRespCode(tmpRespCode);
            retAtsTrans.writeRespInfo(tmpRespInfo);
        } else if (retAtsTrans.getWrittenRdCount() == 0) {
            retAtsTrans.writeRespCode("0");
            retAtsTrans.writeRespInfo("交易为空");
        }
        retAtsTrans.writeEnd();
        return retAtsTrans;
    }

    @Override
    public RetAtsTrans d_7515_TodayTrans(Req7515TodayTrans p_req7515) throws Exception {
        Req7516HisTrans p_req7516 = new Req7516HisTrans(p_req7515.reqHeader);
        p_req7516.actArea = p_req7515.actArea;
        p_req7516.actCur = p_req7515.actCur;
        p_req7516.actNum = p_req7515.actNum;
        String date = Format.Date8Format.format(new Date());
        p_req7516.dateFrom = date;
        p_req7516.dateTo = date;
        return d_7516_HisTrans(p_req7516);
    }
}
